from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet


from meiduo_admin.serializers.orders import OrderInfoSerializer, OrderGoodsSerializer
from meiduo_admin.utils import PageNum
from order.models import OrderInfo


class OrderInfoView(ReadOnlyModelViewSet):
    pagination_class = PageNum
    permission_classes = [IsAdminUser]


    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword is None or keyword == '':
            # 获取全部用户数据
            return OrderInfo.objects.all()
        # 获取关键字查询的数据
        return OrderInfo.objects.filter(order_id__contains=keyword)


    def get_serializer_class(self):
        if self.action == 'retrieve':
            return OrderGoodsSerializer
        else:
            return OrderInfoSerializer
    @action(methods=['put'], detail=True)
    def status(self,request,pk):
        status = request.data['status']
        # 修改订单状态
        order = self.get_object()
        order.status = status
        order.save()
        return Response({
            'order_id':pk,
            'status':order.status
        })